package cn.sh.library.mgts.dto;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

public class SearchExpression {

	private String searchText;
//	private String[] fields = {"TITLE", "AUTHOR", "SUBJECT", "PUBLSHR", "SERIES", "CLC", "ISBN", "ISSN", "ISRC"} ;
	private Map<String, String> mapping = new HashMap<String, String>();
	private List<String> values ;
	private String queryString;
	
	public SearchExpression(String searchText) {
		this.searchText = searchText;
		mapping.put("TITLE", "search.title_keyword");
		mapping.put("AUTHOR", "search.author_keyword");
		mapping.put("SUBJECT", "search.subject_keyword");
		mapping.put("PUBLSHR", "search.publisher_keyword");
		mapping.put("SERIES", "search.series_keyword");
		mapping.put("CLC", "search.clc_term");
		mapping.put("ISBN", "search.isbn_term");
		mapping.put("ISSN", "search.issn_term");
		mapping.put("ISRC", "search.isrc_term");
	}

	public String getSearchText() {
		return searchText;
	}

	public void setSearchText(String searchText) {
		this.searchText = searchText;
	}
	
	public void explainExpression() throws Exception {
		values = new ArrayList<String>();
		queryString = searchText;
		String[] clause =  queryString.split("[()]|[Aa][Nn][dD] |[Oo][Rr] ");
		for(String c: clause) {
			if(StringUtils.isBlank(c)) {
				continue;
			}
			if(!c.contains("=")) {
				throw new Exception("表达式[{" + c + "}]格式不正确！");
			}
			String field = c.split("=")[0];
			values.add(c.split("=")[1]);
			if(!mapping.containsKey(field)) {
				throw new Exception("表达式[{" + c + "}]包含不存在的字段！");
			}
			queryString = queryString.replace(c, mapping.get(field) + ":\"" + c.split("=")[1] + "\"");
		}
		queryString = queryString.replaceAll("[Aa][Nn][dD] ", "AND ").replaceAll("[Oo][Rr] ", "OR ");
		
	}
	
	
	public List<String> getValues() {
		return values;
	}

	public void setValues(List<String> values) {
		this.values = values;
	}
	
	public BoolQueryBuilder getQueryBuilder() throws Exception {
		explainExpression();
		BoolQueryBuilder querybuilder = new BoolQueryBuilder();
		querybuilder.must(QueryBuilders.queryStringQuery(queryString));
		return querybuilder;
	}

	
	public static void main(String[] args) throws Exception {
		String exp = "TITLE=\"马克思\" ";
		System.out.println(exp.matches("(.*)[A-Z]=\\\"(.*)\\\""));
		
//		System.out.println(new SearchExpression(exp).explainExpression());
	}
}
